<?php

class Admin_FeatureController extends My_Controller_Action {

    private $_model = '';
    private $_moduleName = '';
    private $_controllerName = '';
    private $_actionName = '';
    private $_actionMain = '';
    private $_feedback = '';
    private $_params = array();
    private $_userId = '';
    private $_userName = '';

    public function init() {
        My_Auth_User::authenticate();

        $template_path = TEMPLATE_PATH . "/admin";
        $this->loadTemplate($template_path, 'template.ini', 'template');

        $this->_model = new Admin_Model_Feature();
        $this->_moduleName = $this->_request->getModuleName();
        $this->_controllerName = $this->_request->getControllerName();
        $this->_actionName = $this->_request->getActionName();
        $this->_params = $this->_request->getParams();
        $this->_actionMain = '/' . $this->_moduleName . '/' . $this->_controllerName . '/index';

        $this->view->params = $this->_params;
        $this->view->controllerName = $this->_controllerName;

        $auth = Zend_Auth::getInstance();
        $infoUser = $auth->getIdentity();
        $this->_userId = $infoUser['userId'];
        $this->_userName = $infoUser['username'];
    }

    public function indexAction() {
        $this->_redirect("/{$this->_moduleName}/{$this->_controllerName}/show-all");
    }

    public function showAllAction() {
        $feature = $this->_model->getFeature();
        
        $paginator = Zend_Paginator::factory ( $feature );
        $currentPage = $this->_getParam ( "page", 1 );
	
        $paginator->setItemCountPerPage ( PAGE_LIST_COUNT );
        $paginator->setCurrentPageNumber ( $currentPage );
        /**
        $arrFeature = null;

        
        foreach($feature as $key => $value){  
        	$arrFeature[$value['categoryId']]['categoryName'] = $value['categoryName'];
        	$arrFeature[$value['categoryId']][] = $value;        	
        }
        */
     
        $this->view->paginator = $paginator;
        $this->view->feature = $feature;
        //$this->view->arrFeature = $arrFeature;
    }

    public function addAction() {
        $data = $this->_request->getPost();
        $formOptions['categoryPath'] = (isset($data['categoryPath']))?$data['categoryPath']:'';
        $form = new Admin_Form_Feature($formOptions);
        $form = new Admin_Form_Feature();

        $categoryModel = new Admin_Model_Category();
        
        if ($this->_request->isPost()) {
            $valid = new Admin_Form_Validators_FeatureValid($data);
            $categoryPath = $this->_params['categoryPath'];

            if ($form->isValid($data) && $valid->isValid() &&  $categoryPath != null) {
                $data = $form->getValues();
                $data['createdBy'] = $this->_userId;
                $db = Zend_Db_Table::getDefaultAdapter();
                $db->beginTransaction();
                
                try {
                	$categoryFeatureModel = new Admin_Model_CategoryFeature();
                	
                	unset($data['categoryPathOld']);
                	$data['categoryPath'] = implode(',', array_unique($categoryPath));
                	$featureId = $this->_model->addItem($data);
                	
                	$dataCategoryFeature['featureId'] = $featureId;
                	foreach($categoryPath as $item){
                		$dataCategoryFeature['categoryId'] = $item;                		 
                		$categoryFeatureId = $categoryFeatureModel->addItem($dataCategoryFeature);
                	}
                	
                	$db->commit();
                }catch (Exception $e){
                	$db->rollBack();
                	throw $e;
                }
                
                if ($featureId && $categoryFeatureId) {
                    if (isset($this->_params['btnSave'])) {
                        $this->view->popupMessage = $this->_helper->popupMessage(MESS_ADD, $this->_actionMain);
                    } elseif (isset($this->_params['btnSaveAdd'])) {
                        $this->_redirect("/{$this->_moduleName}/{$this->_controllerName}/{$this->_actionName}");
                    }
                }
            } else {
            	if($categoryId == null){ 
            		$valid->messages[] = 'Chưa chọn danh mục sản phẩm';
            	}
                $this->view->error = $valid->messages;
            }
        }

        $this->view->form = $form;
    }

    public function editAction() {
        $featureId = $this->_params['id'];
        
        if ($this->_request->isPost()) {
            $data = $this->_request->getPost();
        } else {
            $data = $this->_model->getFeatureOne($featureId, array('task'=>'category'));            
        }
        
        $featureDetailModel = new Admin_Model_FeatureDetail();
        $featureDetail = $featureDetailModel->getFeatureDetail($featureId, array('task' => 'admin-fetureCategory'));
        
        $arrFeatureDetail = null;
        foreach($featureDetail as $key => $value){
        	$arrFeatureDetail[$value['categoryId']]['categoryName'] = $value['categoryName'];
        	$arrFeatureDetail[$value['categoryId']][] = $value;
        }
        //My_Common::dump($data);die;
        $formOptions['categoryPath'] = (isset($data['categoryPath']))?$data['categoryPath']:'';
        $form = new Admin_Form_Feature($formOptions);

        if ($this->_request->isPost()) {
            $valid = new Admin_Form_Validators_FeatureValid($data);
            $categoryPath = $this->_params['categoryPath'];

            if ($form->isValid($data) && $valid->isValid()) {
                $data = $form->getValues();

                $data['modified'] = date(DATETIME_FORMAT_DB, time());
                $data['modifiedBy'] = $this->_userId;
                
                $db = Zend_Db_Table::getDefaultAdapter();
                $db->beginTransaction();
                
                try {
                	$categoryFeatureModel = new Admin_Model_CategoryFeature();
                	
                	$categoryPathOld = explode(',', $data['categoryPathOld']); 
                	$categoryPathOld = array_unique($categoryPathOld);
                	unset($data['categoryPathOld']);
                	$data['categoryPath'] = implode(',', array_unique($categoryPath));
                	$this->_model->updateItem($featureId, $data);
              
                	$dataCategoryFeature['featureId'] = $featureId;                	
                	foreach($categoryPath as $item){
                		$dataCategoryFeature['categoryId'] = $item;                		
                		if(in_array($item, $categoryPathOld, true)){
	                		$whereUpdate[] = "categoryId = {$item}";
	                		$whereUpdate[] = "featureId = {$featureId}";
	                		$result = $categoryFeatureModel->updateItem($whereUpdate, $dataCategoryFeature);
	                		
	                		$key = array_search($item, $categoryPathOld);
	                		unset($categoryPathOld[$key]);
                		}else{
                			$result = $categoryFeatureModel->addItem($dataCategoryFeature);
                		}                		
                	}
                	
                	if($categoryPathOld != null){
	                	$whereDelete = "categoryId IN (".implode(',', $categoryPathOld).") AND featureId = ".$featureId;	                	
	                	$result = $categoryFeatureModel->deleteItem($whereDelete);
                	}
                	
                	$db->commit();
                }catch (Exception $e){
                	$db->rollBack();
                	throw $e;
                }
                
               
                if (1==1) {
                    if (isset($this->_params['btnSave'])) {
                        $this->view->popupMessage = $this->_helper->popupMessage(MESS_UPDATE, $this->_actionMain);
                    } elseif (isset($this->_params['btnSaveAdd'])) {
                        $this->_redirect("/{$this->_moduleName}/{$this->_controllerName}/add");
                    }
                }
            } else {
                $this->view->error = $valid->messages;
            }
        }
      
        $form->populate($data);
        $this->view->data = $data;
        $this->view->form = $form;
        $this->view->featureDetail = $featureDetail;        
        $this->view->arrFeatureDetail = $arrFeatureDetail;        
    }

    function ajaxEditFeatureAction() {
        $template_path = TEMPLATE_PATH . "/admin";
        $this->loadTemplate($template_path, 'template.ini', 'ajax');
        $this->_helper->viewRenderer->setNoRender();

        $categoryId = $this->_params['id'];
        $field = $this->_params['field'];
        $value = $this->_params['value'];

        $data[$field] = $value;
        $data['modifiedBy'] = $this->_userId;
        $data['modifiedByUserName'] = $this->_userName;

        $result = array(
            'result' => $this->_model->updateItem($categoryId, $data),
            'value' => $value,
        );
        echo json_encode($result);
        die;
    }

    function ajaxDeleteFeatureAction() {
        $template_path = TEMPLATE_PATH . "/admin";
        $this->loadTemplate($template_path, 'template.ini', 'ajax');
        $this->_helper->viewRenderer->setNoRender(); 

        $featureDetailModel = new Admin_Model_FeatureDetail();
        $FeatureId = $this->_params['data'];
        
        $featureDetails = '';//$featureDetailModel->getFeatureDetailByFeatureId($FeatureId);

        if ($featureDetails != NULL) {
            $message = 'Không thể xoá thuộc tính này. Vì có thuộc tính con trong danh mục';
            $message = $this->_helper->popupMessage($message);
            $result = array(
                'result' => 2,
                'value' => $message,
            );
        } else {
            $result = array(
                'result' => $this->_model->deleteItem($FeatureId),
                'value' => $FeatureId,
            );
        }

        echo json_encode($result);
        die;
    }
    
    function ajaxGetCategoryAction() {
        $template_path = TEMPLATE_PATH . "/admin";
        $this->loadTemplate($template_path, 'template.ini', 'ajax');
        
        $Feature = $this->_model->getFetchPairs($this->_params, array('task'=>'by-category'));
        
        $this->view->Feature = $Feature;
    }

}